<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Mage
 * @package     Mage_Shell
 * @copyright   Copyright (c) 2009 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
 * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

require_once 'abstract.php';

/**
 * Magento Compiler Shell Script
 *
 * @category    Mage
 * @package     Mage_Shell
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Shell_Reviews extends Mage_Shell_Abstract
{

	private $_ratingIds = null;
	private $_allStoreIds = null;
	
	private function _getRatingIds()
	{
		if (is_null($this->_ratingIds)){
			$ratings = array();
			$ratingCollection = Mage::getModel('rating/rating')
				->getResourceCollection()
				->addEntityFilter('product')
				->setPositionOrder()
				->load();
			$this->_ratingIds = array_keys($ratingCollection->getItems());
		}
		
		return $this->_ratingIds;
	}
	
	private function _getRandomRatings(){
		$ratings = $this->_getRatingIds();
    	foreach($ratings as $ratingId){
    		$ratings[$ratingId] = mt_rand($ratingId * 5 - 1, $ratingId * 5);
    	}
    	
    	return $ratings;
	}
	
	private function _getRandomProductIds($categoryId, $limit = 5)
	{
		$category = Mage::getModel('catalog/category')->load($categoryId);
		$productCollection = Mage::getModel('catalog/product')->getCollection()
			->addCategoryFilter($category)
			->setCurPage(1)
			->setPageSize($limit)
			->addOrder(new Zend_Db_Expr('RAND()'));
		
		$productIds = array();
		foreach($productCollection->getData() as $product){
			$productIds[] = $product['entity_id'];
		}
		
		return $productIds;
	}
	
	private function _getRandomCurMonthDateTime()
	{
		$startTime = mktime(0, 0, 0, date('n'), 1, date('Y'));
		$endTime = mktime(23, 59, 59, date('n'), date('t'), date('Y'));
		$randomTime = mt_rand($startTime, $endTime);
		
		return date('Y-m-d H:i:s', $randomTime);
	}
	
	private function _randomAddReview($categoryId, $nickName, $title, $review, $limit=5, $stores =1)
	{
		$productIds = $this->_getRandomProductIds($categoryId, $limit);
		
		if (!$productIds){
			return false;
		}
		$data = array(
    		'nickname' => $nickName,
    		'title' => $title,
    		'detail' => $review
    	);
		$defaultStoreId = 1;
		foreach($productIds as $productId){
			$rating = $this->_getRandomRatings();
			$review     = Mage::getModel('review/review')->setData($data);
			$validate = $review->validate();
			if ($validate === true) {
				try {
					$review->setEntityId($review->getEntityIdByCode(Mage_Review_Model_Review::ENTITY_PRODUCT_CODE))
						->setEntityPkValue($productId)
						->setStatusId(Mage_Review_Model_Review::STATUS_APPROVED)
						->setCustomerId(Mage::getSingleton('customer/session')->getCustomerId())
						->setStoreId($defaultStoreId)
						->setStores((array)$stores)
						->save();
			
					$review->setCreatedAt($this->_getRandomCurMonthDateTime())->save();
			
					foreach ($rating as $ratingId => $optionId) {
						Mage::getModel('rating/rating')
							->setRatingId($ratingId)
							->setReviewId($review->getId())
							->setCustomerId(Mage::getSingleton('customer/session')->getCustomerId())
							->addOptionVote($optionId, $productId);
					}
			
					$review->aggregate();
				}
				catch (Exception $e) {
					die($e->getMessage());
				}
			}
		}
			
	}
	private function _getCsvDir()
	{
		$pathArr = array('var', 'import');
		
		return dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . join(DIRECTORY_SEPARATOR, $pathArr);
	}
	protected function _getSourceAdapter($sourceFile)
	{
		return Mage_ImportExport_Model_Import_Adapter::findAdapterFor($sourceFile);
	}
	private function _getAllStoreIds()
	{
		if(is_null($this->_allStoreIds)){
			$this->_allStoreIds = array_keys(Mage::getModel('core/store')->getCollection()->toOptionHash());
		}

		return $this->_allStoreIds;
	}
	/**
     * Run script
     *
     */
    public function run()
    {
        if($this->getArg('csv')){
        	$csvFile = $this->_getCsvDir() . DIRECTORY_SEPARATOR . $this->getArg('csv');
        	if (is_file($csvFile)){
        		$adapter = $this->_getSourceAdapter($csvFile);
        		foreach($adapter as $row){
        			#Zend_Debug::dump($row);
        			if (
        				!isset($row['category']) 
        				|| !isset($row['nickname']) 
        				|| !isset($row['title']) 
        				|| !isset($row['detail']) 
        				|| !isset($row['limit'])
        				|| !isset($row['stores'])
        			){
        				die("invalid content format!");
        			}
        			if (empty($row['stores']) || $row['stores'] == 0){
        				$row['stores'] = $this->_getAllStoreIds();
        			} else {
        				$row['stores'] = explode('|', $row['stores']);
        			}
        			$this->_randomAddReview($row['category'], $row['nickname'], $row['title'], $row['detail'], $row['limit'], $row['stores']);
        		}
        	} else {
        		die("$csvFile is not exist!");
        	}
        	echo "finished!\n";exit;
        } else {
            echo $this->usageHelp();
        }
    }

    /**
     * Retrieve Usage Help Message
     *
     */
    public function usageHelp()
    {
        return <<<USAGE
Usage:  php -f reviews.php -- [options]
        php -f reviews.php -- import --csv test.csv
               
  --csv <reviews>           import random reviews from csv file
  help                          This help

USAGE;
    }
}

$shell = new Mage_Shell_Reviews();
$shell->run();
